//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/subject/upload_save_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/card_label_widget.dart';

/// 显示答题卡
class QuestionDtkWidget extends StatelessWidget {
  /// 是否显示夜间模式
  final bool szYjms;

  /// 做题对应状态
  final QuestionTypeEnum type;

  /// 是否有做题数据
  final bool doing;

  /// 对应数据
  final List<BogInfoModel> list;

  const QuestionDtkWidget({
    super.key,
    required this.list,
    required this.szYjms,
    required this.type,
    required this.doing,
  });

  @override
  Widget build(BuildContext context) {
    debugPrint("questionDtkWidget 组件 -> build 方法执行 ===> ");
    debugPrint("");
    return Container(
      padding: EdgeInsets.symmetric(vertical: 40, horizontal: 30),
      decoration: BoxDecoration(
        color: getColorWhite1(szYjms: szYjms),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      child: Column(
        children: [
          _titleItems(context),
          Expanded(child: _showList(context)),
        ],
      ),
    );
  }

  /// 标题组件
  _titleItems(BuildContext context) {
    return Column(
      children: [
        _titleItem(context),
        hiSpace(height: 24),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            CardLabelWidget(
              szYjms: szYjms,
            )
          ],
        )
      ],
    );
  }

  /// 标题
  _titleItem(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            width: 40,
            height: 40,
          ),
          Text(
            "答题卡",
            style: FontUtil.fontBlack1(28, szYjms: szYjms),
          ),
          _titleItemQk(context),
        ],
      ),
    );
  }

  /// 清空按钮显示
  _titleItemQk(BuildContext context) {
    bool showQk =
        type == QuestionTypeEnum.answer || type == QuestionTypeEnum.memory;
    if (showQk) {
      return GestureDetector(
        onTap: () {
          _onTapFunQk(context);
        },
        child: SvgPicture.asset(
          "images/subject/subject_trash_can.svg",
          width: 32,
          height: 32,
          color: szYjms ? colorWhite1 : null,
        ),
      );
    } else {
      return SizedBox(width: 40, height: 40);
    }
  }

  /// 清空按钮被点击
  _onTapFunQk(BuildContext context) {
    debugPrint("questionDtkWidget 组件 -> 你点击了清空按钮 ===> $doing");
    // 判断是否答题
    if (doing) {
      // 开启加载框
      ToastUtil.loadingBoxShow(context);
      // 发送请求
      PaperDataModel paperData = dataUtilComm.paperData!;
      DataModel dataModel = dataUtilComm.dataModel;
      SubjectDao.cleamCollectRecords(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        recordsType: paperData.rType,
        haveCollect: false,
        id: paperData.id,
      ).then((UploadSaveModel save) {
        // 加载成功，关闭加载框
        ToastUtil.loadingBoxRemove();
        dataUtilComm.paperData!.dc = save.dc;
        dataUtilComm.paperData!.ec = save.ec;
        // dataUtilComm.paperData!.cc = save.cc;
        // 发送通知
        eventBus.fire(EventQuestionQk());
        // 退出答题卡
        Navigator.pop(context);
      }).catchError((e) {
        debugPrint("questionDtkWidget 组件 -> 删除集合做题/错题记录发生异常 ===> $e");
        // 关闭加载框
        ToastUtil.loadingBoxRemove();
        String msg = "未知错误，请重试";
        if (e is DaoException) {
          debugPrint("questionDtkWidget 组件 -> dao异常 ===> ${e.msg}");
          msg = e.msg;
        }
        // 提示
        ToastUtil.show(context: context, msg: msg);
      });
    } else {
      // 未答题，提示或不做处理
    }
  }

  /// 显示数据
  _showList(BuildContext context) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: ListView(
        children:
        list.map((BogInfoModel bog) => _listItem(bog, context)).toList(),
      ),
    );
  }

  /// 显示对应的组件
  Widget _listItem(BogInfoModel bog, BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "${bog.name}（本大题共${bog.total}小题）",
            style: FontUtil.fontBlack1(18, szYjms: szYjms),
          ),
          hiSpace(height: 30),
          _labelItems(bog.dtkList, context),
        ],
      ),
    );
  }

  /// 显示对应的题目数据
  _labelItems(List<DtkInfoModel> qsList, BuildContext context) {
    List<Widget> widgets = [];
    for (int i = 0; i < qsList.length; i++) {
      widgets.add(_labelItem(i + 1, qsList[i], context));
    }
    return Wrap(
      spacing: 20,
      runSpacing: 20,
      children: widgets,
    );
  }

  /// 显示组件
  Widget _labelItem(int i, DtkInfoModel dtk, BuildContext context) {
    Color bgColor;
    if (dtk.ansType == AnswerTypeEnum.success) {
      // 答对
      bgColor = getColorGreen10(szYjms: szYjms);
    } else if (dtk.ansType == AnswerTypeEnum.error) {
      // 答错
      bgColor = getColorRed5(szYjms: szYjms);
    } else {
      // 未答题
      bgColor = getColorGrey10(szYjms: szYjms);
    }

    return GestureDetector(
      onTap: () {
        debugPrint("questionDtkWidget 组件 -> 你点击了 $i ===> ${dtk.index}");
        eventBus.fire(EventQuestionOnDtk(index: dtk.index));
        Navigator.pop(context);
      },
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.all(Radius.circular(35)),
        ),
        child: Center(
          child: Text(
            i.toString(),
            style: TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.w400,
              color: dtk.ansType != AnswerTypeEnum.notDone
                  ? colorWhite1
                  : getColorGrey11(szYjms: szYjms),
            ),
          ),
        ),
      ),
    );
  }
}
